package com.vnzii.chat.fragment;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.vnzii.chat.ChatActivity;
import com.vnzii.chat.R;
import com.vnzii.chat.manager.MyFragment;

public class ModeOffline extends MyFragment implements OnClickListener {

	private Button bt_Server;
	private LinearLayout linear_Server;
	private Button bt_Client;
	private EditText et_ipSever;
	private Button bt_Connect;

	@Override
	public boolean openDatabase() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public int getRootView() {
		// TODO Auto-generated method stub
		return R.layout.layout_mode_offline;
	}

	@Override
	public void getControls(View rootView) {
		bt_Server = (Button) rootView.findViewById(R.id.bt_Server);
		linear_Server = (LinearLayout) rootView
				.findViewById(R.id.linear_Server);
		bt_Client = (Button) rootView.findViewById(R.id.bt_Client);
		et_ipSever = (EditText) rootView.findViewById(R.id.et_ipSever);
		bt_Connect = (Button) rootView.findViewById(R.id.bt_Connect);

		et_ipSever.setText(getLocalIpAddress());
	}

	@Override
	public void addEvents() {
		bt_Server.setOnClickListener(this);
		bt_Client.setOnClickListener(this);
		bt_Connect.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_Server:
			show();
			break;
		case R.id.bt_Client:
			show();
			break;
		case R.id.bt_Connect:
			Intent intent = new Intent(getActivity(), ChatActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}

	}

	public void show() {
		if (linear_Server.getVisibility() == View.GONE) {
			linear_Server.setVisibility(View.VISIBLE);
		} else {
			linear_Server.setVisibility(View.GONE);
		}
	}

	public String getLocalIpAddress() {
		String ip = null;
		try {
			Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
					.getNetworkInterfaces();
			while (enumNetworkInterfaces.hasMoreElements()) {
				NetworkInterface networkInterface = enumNetworkInterfaces
						.nextElement();
				Enumeration<InetAddress> enumInetAddress = networkInterface
						.getInetAddresses();
				while (enumInetAddress.hasMoreElements()) {
					InetAddress inetAddress = enumInetAddress.nextElement();
					if (!inetAddress.isLoopbackAddress()
							&& (inetAddress instanceof Inet4Address)) {
						ip = inetAddress.getHostAddress();
					}
				}
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ip;
	}
}
